//
//  MagazineCollectionController.m
//  Jingjing
//
//  Created by Maxwell Rose on 15/11/12.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "MagazineCollectionController.h"
#import "MagazineCollectionViewCell.h"
#import "MagazineModel.h"
#import "MagazineCollectionModel.h"
#import "BookPageViewController.h"

#define kCellWidth      ((SCREEN_WIDTH - 16*4) / 3.0)
#define kCellHeight     (kCellWidth * 4 / 3.0 + 22)

static NSString *const MagazineCollectionCell = @"MagazineCollectionCell";

@interface MagazineCollectionController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray *dataSources;

@property (strong, nonatomic) UIView *noDataView;

@property (strong, nonatomic) UIView *noNet;

@end

@implementation MagazineCollectionController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataSources = [NSMutableArray array];
    // Do any additional setup after loading the view from its nib.
    [self setupCollectionView];
    [_collectionView.header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,self.view);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 44 -49 - 30) collectionViewLayout:layout];
        NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,self.view);
        [self.view addSubview: _collectionView];
        [_collectionView addSubview:self.noNet];
        [_collectionView addSubview:self.noDataView];
    }
    return _collectionView;
}

/**
 *  设置CollectionView
 */
- (void)setupCollectionView{
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background（750）"]];
    [_collectionView registerNib:[UINib nibWithNibName:@"MagazineCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:MagazineCollectionCell];
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataSources removeAllObjects];
        [_collectionView reloadData];
        [self refresh];
    }];
}

- (void)refresh{
    self.noDataView.hidden = TRUE;
    _noNet.hidden = TRUE;
    
    static NSInteger nextPage = 1;
    if (_dataSources.count == 0) {
        nextPage = 0;
    }
    //发送网络请求获取视频列表
    NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,self.model.typeTitle);
    NSDictionary *parameter = @{@"typeId":self.model.typeId,
                                @"page.pn":[NSNumber numberWithInteger: nextPage == 0 ? 1 : nextPage]
                                };
    //发送网络请求获取视频列表
    [AppGlobalClass PostDataWithNSstring:kLinkOfMagazineList withDictionary:parameter success:^(NSDictionary *dictionary) {
        if ([[dictionary objectForKey:@"success"] isEqualToNumber:@YES])
        {
            NSDictionary *responseDate = [dictionary[@"responseData"] firstObject];
            NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,responseDate);
            NSInteger pages = [responseDate[@"pages"] integerValue];
            NSInteger currentPage = [responseDate[@"page"] integerValue];
            if (nextPage != currentPage) {
                [_dataSources removeAllObjects];
            }
            if (pages > 1) {
                _collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                    [self refresh];
                }];
                nextPage = currentPage + 1;
                if (pages == currentPage) {
                    [_collectionView.footer endRefreshingWithNoMoreData];
                    nextPage = 1;
                }
                
            }else{
                [self.dataSources removeAllObjects];
                [_collectionView reloadData];
                _noDataView.hidden = YES;

            }
            
            NSArray * rowsArray = responseDate[@"rows"];
            for (NSDictionary * dataDict in rowsArray)
            {
                MagazineCollectionModel * model = [[MagazineCollectionModel alloc]init];
                [model setValuesForKeysWithDictionary:dataDict];
                [_dataSources addObject:model];
            }
            if (_dataSources.count > 0)
            {
                [_collectionView reloadData];
                _noDataView.hidden = YES;

            }
            else{
                _noDataView.hidden =FALSE;
            }
        }else{
            //没有真确返回
            [self.dataSources removeAllObjects];
            [_collectionView reloadData];
            _noDataView.hidden = FALSE;
            
        }
        [self.collectionView.header endRefreshing];
        
    } failure:^(NSError *error) {
        NSLog(@"----%@",error);
        _noDataView.hidden = FALSE;
        [_dataSources removeAllObjects];
        [_collectionView reloadData];
        [self.collectionView.header endRefreshing];
        
    } networkerror:^(NSString *networkerror) {
        NSLog(@"----");
        _noNet.hidden = FALSE;
        [_dataSources removeAllObjects];
        [_collectionView reloadData];
        
        [self.collectionView.header endRefreshing];
        
    }];
}

#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//    return self.dataSources.count;
    return _dataSources.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MagazineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:MagazineCollectionCell forIndexPath:indexPath];
    MagazineCollectionModel * model = _dataSources[indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark - UICollection View Delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    MagazineCollectionModel *model = _dataSources[indexPath.row];
    BookPageViewController *bookPageViewCon = [[BookPageViewController alloc]initWithBookID:model.ebookId];
    bookPageViewCon.title = model.title;
    if (self.navigationController) {
        [self.navigationController pushViewController:bookPageViewCon animated:TRUE];
    }else{
        [self.model.navigationController pushViewController:bookPageViewCon animated:YES];
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    
}


#pragma mark - UICollection View Delegate FlowLayout
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}

//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(16, 16, 16, 16);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kCellWidth, kCellHeight);
}

//没网提示
#pragma mark - 没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 235)];
        _noNet.center = CGPointMake(_collectionView.center.x, _collectionView.center.y - 64 - 32);
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:@"加载失败\n请检查手机是否联网"];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.098 alpha:1.000],
                                 } range:NSMakeRange(0, 5)];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.702 alpha:1.000],
                                 } range:NSMakeRange(5, 9)];
        [label setAttributedText:aString];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"重新加载" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_noNet addSubview:btn];
    }
    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noDataView.center =CGPointMake(_collectionView.center.x, _collectionView.center.y - 64 );
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"暂无杂志";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.098 alpha:1.000];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
    }
    
    return _noDataView;
}

- (void)noResultButtonAction:(UIButton *)btn{
    [self.collectionView.header beginRefreshing];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
